package com.audaque.springboot.foshanupload.web.nettydemo.handler;

import cn.hutool.json.JSONUtil;
import com.audaque.springboot.foshanupload.core.util.StringUtils;
import com.audaque.springboot.foshanupload.web.nettydemo.model.req.MessageReq;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class EchoInboundHandlerUtils {
    public static void channelRead(ChannelHandlerContext ctx, Object msg) {
        //首次连接是FullHttpRequest，处理参数
        if (null != msg && msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            //向下传递
            ctx.fireChannelRead(msg);
        } else if (null != msg && msg instanceof TextWebSocketFrame) {
            TextWebSocketFrame msg1 = (TextWebSocketFrame) msg;
            String text = msg1.text();
            TextWebSocketFrame textWebSocketFrame1 = null;
            if (StringUtils.isBlank(text)) {
                textWebSocketFrame1 = new TextWebSocketFrame();
            } else if ("PING".equals(text)) {
                textWebSocketFrame1 = msg1;
            } else if (JSONUtil.isTypeJSON(text)) {
                String json = text;
                MessageReq messageReq = JSONUtil.toBean(json, MessageReq.class);
                String message = messageReq.getMessage();
                System.out.println("EchoInboundHandler1.channelRead 收到数据：" + message);
                if (message != null) {
                    //向下传递
                    message = message + 1;
                    messageReq.setMessage(message);
                }
                //向下传递:类型要一致
                String json1 = JSONUtil.toJsonStr(messageReq);
                textWebSocketFrame1 = new TextWebSocketFrame(json1);
            } else {
                textWebSocketFrame1 = new TextWebSocketFrame(text);
            }
            ctx.fireChannelRead(textWebSocketFrame1);
            //二进制
            //ByteBuf byteBuf = Unpooled.copiedBuffer(json1, CharsetUtil.UTF_8);
            //ctx.fireChannelRead(byteBuf);
            //ctx.writeAndFlush(Unpooled.copiedBuffer("[第一次write] [EchoInboundHandler2] " + data, CharsetUtil.UTF_8));
            // ctx.channel().writeAndFlush(Unpooled.copiedBuffer("测试一下channel().writeAndFlush", CharsetUtil.UTF_8));
            //ctx.writeAndFlush(Unpooled.copiedBuffer("[第二次write] [EchoInboundHandler3] " + data, CharsetUtil.UTF_8));

        }
    }


    public static void userEventTriggeredClose(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;

            String eventType = null;
            switch (event.state()) {
                case READER_IDLE:
                    eventType = "读空闲";
                    SimpleChannelInboundHandler1.readIdleTimes++; // 读空闲的计数加1
                    break;
                case WRITER_IDLE:
                    eventType = "写空闲";
                    // 不处理
                    break;
                case ALL_IDLE:
                    eventType = "读写空闲";
                    // 不处理
                    break;
            }
            System.out.println(ctx.channel().remoteAddress() + "超时事件：" + eventType);
            if (SimpleChannelInboundHandler1.readIdleTimes > 60) {
                System.out.println(" [server]读空闲超过60次，关闭连接");
                ctx.channel().close();
            }
        }
    }



    public static void userEventTriggeredSendHeartbeat(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (IdleState.READER_IDLE.equals((event.state()))) {
                ctx.writeAndFlush("heartbeat").addListener(ChannelFutureListener.CLOSE_ON_FAILURE) ;
            }
        }

    }



}
